#include "UIEvent.h"
#include "UILogger.h"
#include "UIJSONParser.h"
#include <sstream>
#include <string.h>

UIEvent::UIEvent(void)
{
	m_sender		= MODULE_OTHER;
	m_reciever		= MODULE_OTHER;
	m_sessionID		= -1;
	m_pairID		= -1;
	m_timeStamp		= -1;
	m_type			= "";
	m_value			= "";
	m_binaryData	= NULL;
	m_dataLength	= 0;
}

UIEvent::~UIEvent(void)
{
	m_binaryData = NULL;
}

void UIEvent::copyTo(UIEvent* event)
{
	event->m_sender		= m_sender;
	event->m_reciever	= m_reciever;
	event->m_sessionID	= m_sessionID;
	event->m_pairID		= m_pairID;
	event->m_timeStamp	= m_timeStamp;
	event->m_type		= m_type;
	event->m_value		= m_value;
	event->m_dataLength = m_dataLength;
	if (m_binaryData != NULL){
		event->m_binaryData = new unsigned char[m_dataLength];
		memcpy(event->m_binaryData, m_binaryData, m_dataLength);
	}
}

void UIEvent::deserializeJson(std::string jsonString)
{
	std::string strVal;
	double		dVal;
	int			iVal;

	if (UIJSONParser::getString(jsonString, "source", strVal))
		m_sender = getModuleType(strVal);
	if (UIJSONParser::getString(jsonString, "destination", strVal))
		m_reciever = getModuleType(strVal);
	if (UIJSONParser::getDouble(jsonString, "timestamp", dVal))
		m_timeStamp = (long)dVal;
	if (UIJSONParser::getInt(jsonString, "sessionID", iVal))	
		m_sessionID = iVal;
	if (UIJSONParser::getInt(jsonString, "pairID", iVal))
		m_pairID = iVal;
	if (UIJSONParser::getString(jsonString, "content.type", strVal))
		m_type = strVal;
	if (UIJSONParser::getObject(jsonString, "content.value", strVal))
		m_value = strVal;
}

std::string UIEvent::serializeJson(void)
{
	std::stringstream jsonString;
	jsonString << "{";
	jsonString << "\"source\":\"" << UIModuleTypeStrings[m_sender] << "\",";
	jsonString << "\"destination\":\"" << UIModuleTypeStrings[m_reciever] << "\",";
	jsonString << "\"timestamp\":" << m_timeStamp << ",";
	jsonString << "\"sessionID\":" << m_sessionID << ",";
	jsonString << "\"pairID\":" << m_pairID << ",";
	jsonString << "\"content\":{";
	jsonString << "\"type\":\"" << m_type << "\"";
	if (!m_value.empty()) {
		jsonString << "," << "\"value\":" << m_value;	// end of value
	}
	jsonString << "}}";
	return jsonString.str();
}
